package ds_industry_2025.ds.ds02.sjwj

import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.linalg._
import org.apache.spark.ml.feature.{LabeledPoint, Normalizer, VectorAssembler}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.DoubleType
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}

import java.util.Properties

/*
    1、根据子任务一的结果，计算出与用户id为6708的用户所购买相同商品种类最多的前10位用户id（只考虑他俩购买过多少种相同的商品，
    不考虑相同的商品买了多少次），并根据Hive的dwd库中相关表或MySQL数据库shtd_store中相关表，获取到这10位用户已购买过的商品，
    并剔除用户6708已购买的商品，通过计算这10位用户已购买的商品（剔除用户6708已购买的商品）与用户6708已购买的商品数据集中商品的
    余弦相似度累加再求均值，输出均值前5商品id作为推荐使用，将执行结果截图粘贴至客户端桌面【Release\任务C提交结果.docx】中对应
    的任务序号下。

结果格式如下：
------------------------推荐Top5结果如下------------------------
相似度top1(商品id：1，平均相似度：0.983456)
 */
object t3 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t2")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .config("spark.sql.parquet.writeLegacyFormat","true")
      .enableHiveSupport()
      .getOrCreate()

    import spark.implicits._

    val conn=new Properties()
    conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")

    def read(name:String):DataFrame={
      spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false",name,conn)
    }

    val order_detail=read("order_detail")
    val order_info=read("order_info")
    val sku_info=read("sku_info")
    val user_info=read("user_info")

    val users=user_info.select("id").distinct().withColumnRenamed("id","id_1")
    val skus=sku_info.select("id").distinct().withColumnRenamed("id","id_1")

    val order=users.join(order_info,users("id_1")===order_info("user_id"),"inner")
    val detail=skus.join(order_detail,skus("id_1")===order_detail("sku_id"),"inner")

//    val source = order.join(detail)
//      .select("user_id", "sku_id")
//      .distinct()

    val source=spark.table("tzgc.source").distinct()

    val user_6708_skus = source.filter(col("user_id") === 6708)
      .select("sku_id")
      .map(_(0).toString.toDouble)
      .collect()


    val other_users = source.filter(col("user_id") !== 6708)
      .withColumn(
        "p",
        when(col("sku_id").cast(DoubleType).isin(user_6708_skus: _*), lit(1.0)).otherwise(lit(0.0))
      )
      .groupBy("user_id")
      .agg(sum("p").as("some"))
      .orderBy(desc("some"))
      .limit(10)
      .select("user_id")
      .map(_(0).toString.toDouble)
      .collect()

    val other_user_skus = source.filter(col("user_id").isin(other_users: _*))
      .select("sku_id")
      .map(_(0).toString.toDouble)
      .collect()

    //  todo 读取特征工程的答案
    val sku_index = spark.table("tzgc.t2")

    val assembler = new VectorAssembler()
      .setInputCols(sku_index.columns.slice(1,sku_index.columns.length))
      .setOutputCol("features")

    val pipeline = new Pipeline()
      .setStages(Array(assembler))
      .fit(sku_index).transform(sku_index)

    val MapData:Dataset[LabeledPoint] = pipeline.select("id", "features").map(
      r => {
        new LabeledPoint(r(0).toString.toInt, r(1).asInstanceOf[Vector])
      }
    )

    val normalizer = new Normalizer()
      .setInputCol("features")
      .setOutputCol("f")
      .setP(2.0)

    val sku_t = normalizer.transform(MapData)
      .select("label", "f")

    spark.udf.register(
      "cos",
      (v1:DenseVector,v2:DenseVector) =>{
        1 - breeze.linalg.functions.cosineDistance(
          breeze.linalg.DenseVector(v1.values),
          breeze.linalg.DenseVector(v2.values)
        )
      }
    )

    val result = sku_t.crossJoin(sku_t)
      .toDF("label", "f", "label2", "f2")
      .filter(col("label") !== col("label2"))
      .withColumn("cos", expr("cos(f,f2)"))
      .filter(col("label").cast(DoubleType).isin(user_6708_skus: _*))
      .filter(
        !col("label2").cast(DoubleType).isin(user_6708_skus: _*)
        &&
          col("label2").cast(DoubleType).isin(other_user_skus: _*)
      )
      .groupBy("label2")
      .agg(avg("cos").as("avg_cos"))
      .orderBy(desc("avg_cos"))
      .limit(5)

    println("-------推荐top5结果如下-----------")
    result.collect().zipWithIndex.foreach{
      case (r,index) =>
        val id=r.getAs[Double](0).toInt
        val cos=r(1)
        val str=s"相似度top${index+1}(商品id:${id},平均相似度:${cos})"
        println(str)

    }


    spark.close()
  }
}
